package com.supos.plugin.util;

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class FreemarkerUtil {

    /**
     * @param data 模板参数
     * @param saveFile 生成的文件路径+文件名
     * @param templatePath 模板目录
     * @param templateName 模板文件名称
     * @throws IOException
     * @throws TemplateException
     */
    public static void deploy(Map<String, Object> data, String saveFile, String templatePath, String templateName) throws IOException, TemplateException {
        BufferedWriter bw = null;
        FileWriter fw = null;
        OutputStreamWriter oStreamWriter = null;
        try {
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
            cfg.setDefaultEncoding("UTF-8");
//            URL resourceURL = FreemarkerUtil.class.getClassLoader().getResource("freemarker");
            if (templatePath.startsWith(File.separator)) // 外部指定路径
                cfg.setDirectoryForTemplateLoading(new File(templatePath));
            else { // resource资源文件里查找
                URL resourceURL = FreemarkerUtil.class.getClassLoader().getResource("freemarker");
                if ("file".equals(resourceURL.getProtocol())) {
                    cfg.setDirectoryForTemplateLoading(new File(resourceURL.getPath()));
                } else {
                    cfg.setTemplateLoader(new ClassTemplateLoader(FreemarkerUtil.class.getClassLoader(), "freemarker"));
                }
            }
            cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_28));
            Template temp = cfg.getTemplate(templateName);
            File file = new File(saveFile);
            if (!file.getParentFile().exists())
                file.getParentFile().mkdirs();
//            fw = new FileWriter(file);
            oStreamWriter = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
//            bw = new BufferedWriter(fw);
            temp.process(data, oStreamWriter);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                if (bw != null) bw.flush();
                if (fw != null) fw.close();
            } catch (IOException ignore) {


            }
        }
    }

    public static void main(String[] args) throws IOException, TemplateException {
        String projectPath = System.getProperty("user.dir");
        String s = File.separator;
        System.out.println(System.getProperty("user.dir"));
        Map<String,Object> map = new HashMap<>();
        map.put("apiVersion","111");
        map.put("vendorName","222");
        deploy(map,System.getProperty("user.dir") + "\\app.yaml","","demo.ftl");
    }
}
